package com.xx.happychatboot.middleware.springsecurity.filter;

import com.xx.happychatboot.base.constant.RedisConstant;
import com.xx.happychatboot.base.utils.RedisUtils;
import com.xx.happychatboot.middleware.springsecurity.exception.KaptchaNotMatchException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 前后端分离处理验证码
 */
@Slf4j
public class LoginKaptchaFilter extends UsernamePasswordAuthenticationFilter {

    public static final String FORM_KAPTCHA_KEY = "kaptcha";

    public static final String FORM_KAPTCHA_UUID_KEY = "kaptchaUuid";

    private String kaptchaParameter = FORM_KAPTCHA_KEY;
    private String kaptchaUuidParameter = FORM_KAPTCHA_UUID_KEY;

    public String getKaptchaParameter() {
        return kaptchaParameter;
    }

    public String getFormKaptchaUuidKey() {
        return kaptchaUuidParameter;
    }

    public void setKaptchaParameter(String kaptchaParameter) {
        this.kaptchaParameter = kaptchaParameter;
    }

    public void setFormKaptchaUuidKey(String kaptchaUuidParameter) {
        this.kaptchaUuidParameter = kaptchaUuidParameter;
    }

    /**
     * 前后端分离
     *
     * @param request
     * @param response
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        // 1.获取请求数据
        //⽤来获取数据中验证码
        String kaptcha = request.getParameter(getKaptchaParameter());
        // ⽤来接收⽤户名
        String username = new String(Base64.decodeBase64(request.getParameter(getUsernameParameter())));
        // ⽤来接收密码
        String password = new String(Base64.decodeBase64(request.getParameter(getPasswordParameter())));
        // 用来接受UUID
        String uuid = request.getParameter(getFormKaptchaUuidKey());
        // 是否记住我
        String rememberValue = request.getParameter(AbstractRememberMeServices.DEFAULT_PARAMETER);
        if (StringUtils.isNotBlank(rememberValue)) {
            request.setAttribute(AbstractRememberMeServices.DEFAULT_PARAMETER, rememberValue);
        }

        log.info("用户名:" + username + "密码" + password + "是否记住我：" + rememberValue);

        // 2.通过UUID从redis中获取code
        String redisCode = RedisUtils.getStr(RedisConstant.KAPTCHA + uuid);
        if (StringUtils.isBlank(redisCode)) {
            throw new KaptchaNotMatchException("验证码已过期请重新获取!");
        }

        if (!ObjectUtils.isEmpty(kaptcha) &&
                !ObjectUtils.isEmpty(redisCode) &&
                kaptcha.equalsIgnoreCase(redisCode)) {
            // 3.获取⽤户名 和密码认证
            UsernamePasswordAuthenticationToken authRequest
                    = new UsernamePasswordAuthenticationToken(username, password);
            setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }

        throw new KaptchaNotMatchException("验证码不匹配!");
    }
}
